﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;

public class GameCBTool : EditorWindow
{
    Mesh mesh;
    bool invTra = false;
    bool invNormal = false;
    bool swapUV = false; // ✅ 新增：是否交换 UV（U↔V）

    [MenuItem("TA/辅助/GPA UV合并工具")]
    static void Init()
    {
        EditorWindow.GetWindow<GameCBTool>("图层通道合并工具").Show();
    }

    void OnGUI()
    {
        mesh = (Mesh)EditorGUILayout.ObjectField("Mesh", mesh, typeof(Mesh), false);
        invTra = EditorGUILayout.Toggle("三角形翻转", invTra);
        invNormal = EditorGUILayout.Toggle("法线反转", invNormal);
        swapUV = EditorGUILayout.Toggle("UV翻转（U↔V）", swapUV); // ✅ 新增 UI
        if (GUILayout.Button("合成"))
        {
            CombinCMJH();
        }
    }

    private void CombinCMJH()
    {
        if (mesh == null)
        {
            Debug.LogWarning("请先指定 Mesh 对象！");
            return;
        }

        string path = AssetDatabase.GetAssetPath(mesh);

        if (path.ToLower().EndsWith(".obj"))
        {
            string csv_path = path.Substring(0, path.Length - 3) + "csv";

            if (File.Exists(csv_path))
            {
                // ✅ 备份原始 OBJ（可选）
                /*string bakPath = path + ".bak";
                if (!File.Exists(bakPath))
                    File.Copy(path, bakPath);*/

                AddUVToObject(path, csv_path);
                AssetDatabase.ImportAsset(path);
                invTra = false;
                invNormal = false;
                swapUV = false;
            }
        }

        Debug.Log("处理完成: " + path);
    }

    bool AddUVToObject(string ObjPath, string CsvPath, int index0 = 1)
    {
        char[] spes = new char[1] { '/' };
        char[] spesSp = new char[1] { ' ' };
        try
        {
            if (!File.Exists(ObjPath))
            {
                Debug.LogError("OBJ 路径不存在: " + ObjPath);
                return false;
            }

            if (!File.Exists(CsvPath))
            {
                Debug.LogError("CSV 路径不存在: " + CsvPath);
                return false;
            }

            string[] lines = File.ReadAllLines(ObjPath);
            string[] csvs = File.ReadAllLines(CsvPath);

            List<string> finals = new List<string>();
            int index = 0;

            // 加入 v
            for (; index < lines.Length; index++)
            {
                string line = lines[index];
                if (line.StartsWith("v "))
                    finals.Add(line);
                else
                    break;
            }

            // 跳过原有 vt
            for (; index < lines.Length; index++)
            {
                if (!lines[index].StartsWith("vt "))
                    break;
            }

            // 加入新 vt
            for (int i = 1; i < csvs.Length; i += 2)
            {
                string l1 = csvs[i];
                string l2 = csvs[i + 1];
                string[] arrays1 = l1.Split(',');
                string[] arrays2 = l2.Split(',');

                double u = double.Parse(arrays1[index0]);
                double v = double.Parse(arrays2[index0]);

                while (u > 1f) u -= 1f;
                while (u < 0) u += 1f;
                while (v > 1f) v -= 1f;
                while (v < 0) v += 1f;

                v = 1 - v; // OpenGL to Unity 坐标系翻转

                // ✅ 判断是否交换 UV
                if (swapUV)
                {
                    var temp = u;
                    u = v;
                    v = temp;
                }

                finals.Add($"vt {u} {v}");
            }

            // 加入 vn
            for (; index < lines.Length; index++)
            {
                string line = lines[index];
                if (line.StartsWith("vn "))
                {
                    if (invNormal)
                    {
                        string[] parts = line.Split(spesSp, StringSplitOptions.RemoveEmptyEntries);
                        float x = -float.Parse(parts[1]);
                        float y = -float.Parse(parts[2]);
                        float z = -float.Parse(parts[3]);
                        finals.Add($"{parts[0]} {x} {y} {z}");
                    }
                    else
                    {
                        finals.Add(line);
                    }
                }
                else
                {
                    break;
                }
            }

            // 处理 f 行
            for (; index < lines.Length; index++)
            {
                string line = lines[index];

                if (line.StartsWith("f "))
                {
                    string[] parts = line.Split(spesSp, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length < 4) continue;

                    if (invTra)
                    {
                        // 交换三角形第二和第三个顶点
                        var tmp = parts[1];
                        parts[1] = parts[2];
                        parts[2] = tmp;
                    }

                    string newLine = "f";
                    for (int j = 1; j < parts.Length; j++)
                    {
                        string[] tokens = parts[j].Split(spes, StringSplitOptions.RemoveEmptyEntries);
                        if (tokens.Length == 3)
                        {
                            newLine += $" {tokens[0]}/{tokens[1]}/{tokens[2]}";
                        }
                        else
                        {
                            newLine += $" {tokens[0]}/{tokens[0]}/{tokens[0]}";
                        }
                    }
                    finals.Add(newLine);
                }
                else
                {
                    finals.Add(line);
                }
            }

            File.WriteAllLines(ObjPath, finals);
            Debug.Log("✅ 合并完成: " + ObjPath);
            AssetDatabase.Refresh();
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError("❌ 合并失败，可能是格式错误或数据缺失\n" + e.Message);
            return false;
        }
    }
}
